package cn.edu.hziee;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

public class LastAccessServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String  lastAccessTime = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if ("lastAccess".equals(cookie.getName())){
                lastAccessTime = cookie.getValue();
                break;
            }
        }

        if (lastAccessTime == null){
            out.println("首次访问");
        }else{
            out.println("上一次访问时间："+lastAccessTime);
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd#hh:mm:ss");
        Cookie cookie = new Cookie("lastAccess",sdf.format(date));
        response.addCookie(cookie);
    }
}
